package wechat.handler.work;

import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import wechat.handler.util.StreamUtil;
import wechat.handler.work.template.SendTempleHandler;
import wechat.handler.work.webauth.WebAuthHandler;

public class WechatServiceHandler {
	private Logger log = LoggerFactory.getLogger(WechatServiceHandler.class);
	
	public WechatServiceHandler(){
		
	}
	
	
	public String process(InputStream dataInputStream) {
		
		String str = StreamUtil.inputStreamToString(dataInputStream);
		System.out.println(str);
		log.info("WechatServiceHandler--Process str=" + str);


		JSONObject reqJson = JSON.parseObject(str);
		
		String actionKKPAY = reqJson.getString("actionKKPAY");
		String appid = reqJson.getString("appid");
		JSONObject resultJson = new JSONObject();
	
		if (actionKKPAY.equals("auth")) {
			WebAuthHandler webAuthHandler = new WebAuthHandler();
			String code = reqJson.getString("code");
			String state = reqJson.getString("state");
			try {
				
				resultJson = webAuthHandler.getAuthInfo(code, state);
				resultJson.put("msg", "success");
				resultJson.put("code", "1");
				
			} catch (Exception e) {
				log.error("WechatServiceHandler -- getAuthInfo fail",e);
				resultJson.put("msg", "");
				resultJson.put("code", "0");
				e.printStackTrace();
			}

		} else if (actionKKPAY.equals("sendTemplate")) {
			SendTempleHandler sendTempleHandler = new SendTempleHandler();
			try {
				
				sendTempleHandler.sendTemple(appid,reqJson);
				resultJson.put("msg", "success");
				resultJson.put("code", "1");
				
			} catch (Exception e) {
				log.error("WechatServiceHandler -- sendTemple fail",e);
				resultJson.put("msg", "");
				resultJson.put("code", "0");
				e.printStackTrace();
			}
		}

		log.info("WechatServiceHandler--Process resultJson=" + resultJson);
		
		return resultJson.toJSONString();
	}
}
